package com.itzyf.pokemondata.activity.panel

import android.app.Activity
import android.content.Intent
import android.text.TextUtils
import android.view.Menu
import android.view.MenuItem
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.itzyf.pokemondata.R
import com.itzyf.pokemondata.bean.DbDivPokemon
import com.itzyf.pokemondata.utils.OnRefreshListener
import com.itzyf.pokemondata.utils.setOnRefreshListener
import com.qmuiteam.qmui.widget.dialog.QMUIDialog
import com.tydic.baselibrary.activity.BaseActivity
import kotlinx.android.synthetic.main.activity_list.*
import org.litepal.LitePal

class CustomizeActivity : BaseActivity() {
    private lateinit var mAdapter: ItemAdapter
    var mDatas: MutableList<DbDivPokemon?> = ArrayList()
    var index = 0
    override fun handlerActivity() {
        rv_list.layoutManager = LinearLayoutManager(this)
        mAdapter = ItemAdapter(R.layout.item_text, mDatas)
        rv_list.adapter = mAdapter
        mSearchView.hint = "请输入名称"
        queryDatas()

        mAdapter.setOnLoadMoreListener({ queryDatas(index++) }, rv_list)

        pull_to_refresh.setOnRefreshListener(object : OnRefreshListener {
            override fun onRefresh() {
                index = 0
                queryDatas(index)
            }
        })

        mBtnSearch.setOnClickListener {
            val query = mSearchView.text.toString()
            queryDatas(query = query)
        }
        mSearchView.setOnEditorActionListener(TextView.OnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                val query = mSearchView.text.toString()
                queryDatas(query = query)
                return@OnEditorActionListener true
            }
            false
        })

        mAdapter.setOnItemClickListener { _, _, position ->
            val data = mDatas[position]
            data?.let {
                val intent = Intent(this@CustomizeActivity, PanelDetailActivity::class.java)
                intent.putExtra("title", it.pokemonName)
                intent.putExtra("panel", arrayOf(it.hp, it.pa, it.pd, it.sa, it.sd, it.speed).toIntArray())
                intent.putExtra("skin", "")
                intent.putExtra("specialTraining", it.specialTraining)
                intent.putExtra("red1", "")
                startActivity(intent)
            }
        }

        mAdapter.setOnItemLongClickListener { _, _, position ->
            val builder = QMUIDialog.CheckableDialogBuilder(this)
                .addItems(arrayOf("编辑", "删除")) { dialog, which ->
                    if (which == 0) {
                        val intent = Intent(this, EditPokemonActivity::class.java)
                        intent.putExtra("id", mDatas[position]!!.id)
                        startActivityForResult(intent, 0x2)
                    } else {
                        delete(position)
                    }
                    dialog.dismiss()
                }
            builder.show()
            return@setOnItemLongClickListener true
        }
    }

    private fun delete(position: Int) {
        showAlertDialog(
            "提示", "是否删除？", "删除"
        ) { _, _ ->
            LitePal.delete(DbDivPokemon::class.java, mDatas[position]!!.id)
            queryDatas()
        }
    }

    /**
     * 查询数据
     */
    fun queryDatas(index: Int = 0, pageSize: Int = 20, query: String = "") {
        var where = ""
        if (!TextUtils.isEmpty(query)) {
            where = "pokemonName like '%$query%'"
        }
        val dataList =
            LitePal
                .limit(pageSize)
                .offset(index * pageSize)
                .order("createdAt desc")
                .where(where)
                .find(DbDivPokemon::class.java)
        if (index == 0) {
            mDatas.clear()
            pull_to_refresh.finishRefresh()
        }

        mDatas.addAll(dataList)

        if (dataList.size < pageSize) {
            mAdapter.loadMoreEnd()
        } else {
            mAdapter.loadMoreComplete()
        }
        mAdapter.notifyDataSetChanged()

    }

    override fun getContentViewId() = R.layout.activity_list

    override fun getToolbarTitle() = "自定义面板"

    class ItemAdapter(layoutResId: Int, data: List<DbDivPokemon?>) :
        BaseQuickAdapter<DbDivPokemon, BaseViewHolder>(layoutResId, data) {
        override fun convert(helper: BaseViewHolder?, item: DbDivPokemon?) {
            helper?.setText(R.id.text, item?.pokemonName)
        }

    }

    override
    fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.add, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        item?.let {
            when (it.itemId) {
                R.id.action_add -> {
                    val intent = Intent(this, EditPokemonActivity::class.java)
                    startActivityForResult(intent, 0x2)
                }
                R.id.action_clear -> {
                    LitePal.deleteAll(DbDivPokemon::class.java)
                }
                else -> {
                }
            }
            queryDatas()
        }
        return super.onOptionsItemSelected(item)
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 0x2) {
                queryDatas()
                return
            }
        }

    }
}